<script setup>
import { ref, computed ,watchEffect,watch } from 'vue';
import { postService } from "@/services/PostService.js";
import CommentSection from '../Comment/CommentSection.vue';
import DOMPurify from 'dompurify';
import { userServie } from "@/services/user_service.js";
import { userManager } from "@/utils/user.js";
import { ElMessage, ElButton } from 'element-plus';
import LikeButton from '../Forum/LikeButton.vue';

const props = defineProps({ article: { type: Object, required: true } });
const emits = defineEmits(['toggleLike','view-article']);

const showComments = ref(false);
const comments = ref([]);
const isLoadingComments = ref(false);
const username = ref('');

watchEffect(async () => {
  if (props.article && props.article.authorId) {
    try {
      const user = await userServie.getUserById(props.article.authorId);
      username.value = user.username || '未知作者';
    } catch (error) {
      username.value = '未知作者';
    }
  }
});

const snippet = computed(() => {
  if (!props.article.content) return '';
  const sanitized = DOMPurify.sanitize(props.article.content, { ALLOWED_TAGS: [] });
  return (sanitized.substring(0, 120) || '') + (sanitized.length > 120 ? '...' : '');
});

const formatDate = (dateValue) => new Date(dateValue).toLocaleDateString();

const fetchComments = async () => {
  isLoadingComments.value = true;
  try {
    comments.value = await postService.getCommentsByPostId(props.article.id);
  } catch (error) {
    console.error("加载评论失败:", error);
  } finally {
    isLoadingComments.value = false;
  }
};

const toggleComments = async () => {
  showComments.value = !showComments.value;
  if (showComments.value && comments.value.length === 0) {
    await fetchComments();
  }
};

const handleAddNewComment = async (commentContent) => {
  try {
    await postService.createComment({
      contenter: userManager.getUserId(),
      postId: props.article.id,
      content: commentContent,
    });
    ElMessage.success('评论发表成功！');
    if (props.article.commentCount !== undefined) props.article.commentCount++;
    await fetchComments();
  } catch (error) {
    ElMessage.error('评论失败，请稍后重试');
  }
};

const viewArticleDetail = () => emits('view-article', props.article);
</script>

<template>
  <div class="article-item-card">
    <div class="article-main" @click="viewArticleDetail">
      <h3 class="article-title">{{ article.title }}</h3>
      <p class="article-snippet">{{ snippet }}</p>
    </div>
    <div class="article-footer">
      <div class="author-info">{{ username }} · {{ formatDate(article.createTime) }}</div>
      <div class="actions">
        <LikeButton :likes="article.likes" :is-liked="article.liked === true" @toggle-like="$emit('toggleLike', article.id)" />
        <el-button text @click="toggleComments">💬 {{ article.commentCount || 0 }}</el-button>
      </div>
    </div>
    <div v-if="showComments" class="comment-section-wrapper">
      <CommentSection :comments="comments" @add-comment="handleAddNewComment" :is-loading="isLoadingComments" />
    </div>
  </div>
</template>

<style scoped>
.article-item-card { background-color: #fff; padding: 20px; transition: background-color 0.2s ease; }
.article-item-card:hover { background-color: #fafafa; }
.article-main { cursor: pointer; }
.article-title { color: #1d2129; font-size: 18px; font-weight: 600; margin: 0 0 8px 0; }
.article-snippet { color: #4e5969; font-size: 14px; line-height: 1.7; margin-bottom: 16px; }
.article-footer { display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: #86909c; }
.actions { display: flex; align-items: center; gap: 8px; }
.comment-section-wrapper { margin-top: 16px; padding-top: 16px; border-top: 1px dashed #e5e6eb; }
</style>